package com.kitty.game.pet.handler.upgrade;

import com.kitty.game.pet.model.Pet;
import com.kitty.game.role.model.Role;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.pet.message.RespPetEnchantEnd;
import com.kitty.mina.message.MessagePusher;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

@Component
public class EnchantPetHandler extends UpgradePetHandler {
    private static final String SUCCESS_MSG = "恭喜，你的#Y{0}#n获得#R{1}#n灵气，当前点化进度#R{2}%#n。";
    private static final String ERROR_MSG = "该宠物已经完成点化，无法提升灵气。";
    private static final String NO_OPEN = "该宠物还未开启点化，无法提升灵气。";


    @Override
    public String acceptUpgradePet(Role role, Pet pet, String ids, String itemPos, String costType, String otherPetPos) {
        if (pet.getEnchant() == 2) {
            return ERROR_MSG;
        } else if (pet.getEnchant() == 0) {
            return NO_OPEN;
        }
        int limitNum = 0;//限制物品数量
        List<RoleEquip> equips = new ArrayList<>();
        for (String ss : itemPos.split("\\|")) {
            RoleEquip roleEquip = equipService.getRoleEquipByPos(role, Short.parseShort(ss));
            if (roleEquip == null) {
                continue;
            }
            if (roleEquip.isLimit()) {
                limitNum++;
            }
            equips.add(roleEquip);
        }
        int totalNimbus = getEnchantNimbusByItems(role, equips);
        petService.addLimitTime(pet, limitNum);
        setEnchantValue(pet, totalNimbus);
        pet.setEnchant_v(pet.getEnchant_v() + totalNimbus);
        double percent = (double) pet.getEnchant_v() / (double) pet.getEnchant_k();
        String resultMessage;
        if (pet.getEnchant_v() >= pet.getEnchant_k()) {
            pet.setEnchant_v(0);
            pet.setEnchant_k(0);
            pet.setEnchant((byte) 2);
            resultMessage = "恭喜，你的#Y" + pet.getNickname() + "#n点化完成#n。";
        } else {
            String percentMsg = "%.2f";
            percentMsg = String.format(percentMsg, (percent * 100));
            resultMessage = MessageFormat.format(SUCCESS_MSG, pet.getName(), String.valueOf(totalNimbus), percentMsg);
        }
        petService.refreshPetInfo(role, pet);
        refreshPetField(role, pet);
        RespPetEnchantEnd RespPetEnchantEnd = new RespPetEnchantEnd();
        MessagePusher.pushMessage(role, RespPetEnchantEnd);

        return resultMessage;
    }
}
